package com.w2e.travel.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.w2e.travel.client.UserClient;
import com.w2e.travel.entity.Travelogue;
import com.w2e.travel.mapper.TravelogueMapper;
import com.w2e.travel.service.ITravelogueService;
import com.w2e.travel.service.TravelogueViewService;
import com.w2e.travel.vo.UploadProperties;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;
import com.w2e.common.utils.Result;
import com.w2e.common.utils.UploadUtils;

import java.io.File;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yyyl
 * @since 2024-06-29
 */
@RestController
@RequestMapping("/travelogues")
@RequiredArgsConstructor
public class TravelogueController {

    private final UserClient userClient;

    private final TravelogueMapper travelogueMapper;

    private final ITravelogueService travelogueService;

    private final UploadProperties properties;

    private final TravelogueViewService travelogueViewService;

    @GetMapping("action/view")
    public String viewTravelogue(@RequestParam int travelogueId) {
        // 记录浏览量
        travelogueViewService.recordTravelogueView(travelogueId);
        return "";
    }

    // 获取游记浏览量
    @GetMapping("/action/views")
    public long getTravelogueViews(@RequestParam int travelogueId) {
        return travelogueViewService.getTravelogueViews(travelogueId);
    }

    @PostMapping("addNew")
    public Result writeTravelogue(@RequestBody Travelogue travelogue){
        Result result = userClient.isExist(travelogue.getUserId());
        if (result.getCode() == 200){
            if (travelogue.getTravelogueId() == null || travelogue.getTravelogueId() == 0){
                //还没添加进去数据库
                travelogue.setCreatedTime(LocalDateTime.now());
                travelogue.setViewCount(0);
                travelogue.setFlag(0);
                travelogueMapper.insert(travelogue);

                // 获取刚插入的 travelogue 的主键值
                Integer travelogueId = travelogue.getTravelogueId();
                result.setData(travelogueId);
            }else{
                travelogue.setUpdateTime(LocalDateTime.now());
                travelogueService.updateById(travelogue);
                System.out.println(travelogue);
                result.setData(travelogue.getTravelogueId());
            }
            return result;
        }
        return result;
    }

    @PostMapping("upload")
    public Result upload(@RequestParam("file")MultipartFile file) throws IOException, NoSuchAlgorithmException {
        String diskPath = properties.getMapping().get("image");
        //获取源文件名
        String filename = file.getOriginalFilename();
        //获取后缀
        String suffix = filename.substring(filename.lastIndexOf("."));
        String newFileName = UUID.randomUUID().toString().substring(0,8) + suffix;
        File fileObj = new File(diskPath,newFileName);
        //file.transferTo(fileObj) 的作用是将一个文件的内容直接传输到另一个文件。
        //具体来说，file 是要传输内容的源文件，而 fileObj 则是目标文件，表示要将内容传输到的文件对象。
        // 通过调用 transferTo() 方法，源文件的内容会被直接传输到目标文件中，达到文件内容的快速传输或复制的效果。
        // 将 MultipartFile 转换为 File 对象
        File tempFile = File.createTempFile("temp",suffix);
        file.transferTo(tempFile);


        // 判断是否重复
        String existingFileName = UploadUtils.isDuplicate(tempFile, diskPath);
        if (existingFileName != null) {
            //文件已经存在
            tempFile.delete();
            existingFileName = "image/" + existingFileName;
        } else {
            //文件不存在
            file.transferTo(fileObj);
            existingFileName = "image/" + newFileName;
        }
        return new Result(200,existingFileName,"");
    }


    @GetMapping("getDraft")
    public Result getDraftByUid(@RequestParam("userId")Integer id){
        LambdaQueryWrapper<Travelogue> lqw = new LambdaQueryWrapper();
        lqw.eq(Travelogue::getUserId,id);
        lqw.eq(Travelogue::getIsDraft,1);
        List<Travelogue> list = travelogueMapper.selectList(lqw);
        return new Result(200,list,"");
    }

    @DeleteMapping("delDraft")
    public Result delDraftById(@RequestParam("travelogueId")Integer id){
        travelogueMapper.deleteById(id);
        return new Result(200,null,"删除草稿成功！");
    }

    @GetMapping("getOne")
    public Result getOneById(@RequestParam("travelogueId")Integer id){
        Travelogue travelogue = travelogueService.getById(id);
        return new Result(200,travelogue,"");
    }

    @GetMapping("/action/query")
    public Map<String,Object> pageUp(String title,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "5") int size){

        //PageHelper 必须在查询方法前一行执行分页的设置
        //通过插件在后台直接获取数据，设置到p中
        Page<Object> p = PageHelper.startPage(page, size);

        List<Travelogue> travelogues = travelogueMapper.selectLikeTitle(title);

        Map<String,Object> res = new HashMap<>();
        res.put("total",p.getTotal());
        res.put("rows",p);

        return res;
    }

    @GetMapping("/action/queryNewAndHot")
    public Map<String,Object> queryNewAndHot(@RequestParam("flag") Integer flag,
                                             @RequestParam(defaultValue = "1") int page,
                                             @RequestParam(defaultValue = "5") int size){
        //PageHelper 必须在查询方法前一行执行分页的设置
        //通过插件在后台直接获取数据，设置到p中
        Page<Object> p = PageHelper.startPage(page, size);

        if (flag == 1){
            List<Travelogue> travelogues = travelogueMapper.selectNewAndHot();
        }else{
            List<Travelogue> travelogues = travelogueMapper.selectLikeTitle(null);
        }


        Map<String,Object> res = new HashMap<>();
        res.put("total",p.getTotal());
        res.put("rows",p);

        return res;
    }

}
